from bcdbd.rpc.plugins import base
import httplib,libxml2

SUBSCRIPTIONID="0ETJW4K4VNMG1YN61HR2" # BLBARC key :)

class Amazon(base.BasePlugin):
	def request(self, urlargs):
		conn = httplib.HTTPConnection("webservices.amazon.fr")
		
		# Build the request string from urlargs
		rstr = ""
		for i in urlargs:
			rstr += "&%s=%s" % (i, urlargs[i])
			
		conn.request("GET", "/onca/xml?Service=AWSECommerceService&SubscriptionId=%s&AssociateTag=deliciousmons-22&Version=2005-07-27%s" % (SUBSCRIPTIONID, rstr))
		r1 = conn.getresponse()
		return r1.read()
		
	def getBarcode(self, barcode):
		def fillXmlField(fields, nodes, name):
			if (len(nodes) == 1):
				fields[name] = nodes[0].getContent()
			elif (len(nodes) > 1):
				for fieldnum in range(1,len(nodes)+1):
					fields[name+" "+str(fieldnum)] = nodes[fieldnum-1].getContent()
		
		# We can get the ISBN from the barcode
		isbn = barcode[3:12]
		
		# Here we calculate the digit
		avgsum = 0
		for i in range(0,len(isbn)):
			avgsum += int(isbn[i])*(10-i)
		
		key = 11 - (avgsum % 11)
			
		if key != 10:
			isbn += str(key)
		else:
			isbn += "X"
		
		fields = {}
		name = ""
			
		doc = libxml2.parseDoc(self.request({'Operation': 'ItemLookup', 'ResponseGroup': 'Large', 'ItemId': isbn}))
		ctxt = doc.xpathNewContext()
		ctxt.xpathRegisterNs("aws","http://webservices.amazon.com/AWSECommerceService/2005-07-26")
			
		name = ctxt.xpathEval("//aws:Items/aws:Item/aws:ItemAttributes/aws:Title")[0].getContent()
		fillXmlField(fields,ctxt.xpathEval("//aws:Items/aws:Item/aws:ItemAttributes/aws:Author"),"Author")
		fillXmlField(fields,ctxt.xpathEval("//aws:Items/aws:Item/aws:ItemAttributes/aws:Publisher"),"Publisher")
		fillXmlField(fields,ctxt.xpathEval("//aws:Items/aws:Item/aws:ItemAttributes/aws:NumberOfPages"),"Number of pages")
		fillXmlField(fields,ctxt.xpathEval("//aws:Items/aws:Item/aws:ItemAttributes/aws:ProductGroup"),"Type")
		fillXmlField(fields,ctxt.xpathEval("//aws:Items/aws:Item/aws:ItemAttributes/aws:PublicationDate"),"Publication date")
			
		doc.freeDoc()
		ctxt.xpathFreeContext()
		return base.Barcode(barcode, name, fields)